<?php
/**************************************************************************
 * Naanal PHP Framework, Simple, Efficient and Developer Friendly
 * Copyright (C) <2010>  <Tamil Amuthan. R>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ************************************************************************/

class ClsNaanalMenu
{
	///key1 as module and key2 as action and key3 as switch and value as URL
	private $arrMenu=array();
        private $name='';
	function __construct($arrMenu=array(),$name="")
	{
            $this->arrMenu=$arrMenu;
            $this->name=empty($name)?"menu":$name;
	}
        public static function &getInstance($name)
        {
            static $objMenu=null;
            if(is_null($objMenu))
            {
                $objMenu=new ClsNaanalMenu(array(),$name);
            }
            return $objMenu;
        }
        function getModuleMenus()
        {
            $arrModule=getModuleList();
            $arrRows=array();
            foreach($arrModule as $module)
            {
                if(file_exists(NAANAL_APP_PATH."modules/".$module."/menu.php"))
                {
                    include(NAANAL_APP_PATH."modules/".$module."/menu.php");
                    if(isset($menu)) 
                    {
                        foreach($menu as $func)
                        {
                            $tmpArr=$func("home");
                            $tmpArr["module"]=isset($tmpArr["module"])?$tmpArr["module"]:$module;
                            $tmpArr["sort"]=isset($tmpArr["sort"])?$tmpArr["sort"]:0;
                            if(isset($tmpArr["javascript"]) && $tmpArr["javascript"]!==false)
                            {
                                $arrRows[]=array("sort"=>$tmpArr["sort"],"name"=>$tmpArr["name"],"parent"=>$tmpArr["parent"],"caption"=>$tmpArr["caption"],"module"=>$tmpArr["module"],"action"=>$tmpArr["action"],"switch"=>$tmpArr["switch"],"controlpanel"=>$tmpArr["controlpanel"],"isadmin"=>$tmpArr["isadmin"],"url"=>$tmpArr["url"],"javascript"=>$tmpArr["javascript"]);
                            }
                            else
                            {
                                $arrRows[]=array("sort"=>$tmpArr["sort"],"name"=>$tmpArr["name"],"parent"=>$tmpArr["parent"],"caption"=>$tmpArr["caption"],"module"=>$tmpArr["module"],"action"=>$tmpArr["action"],"switch"=>$tmpArr["switch"],"controlpanel"=>$tmpArr["controlpanel"],"isadmin"=>$tmpArr["isadmin"],"url"=>$tmpArr["url"]);
                            }
                        }
                        unset($menu);
                    }
                }
            }
            // covert raw result set to tree
            $menu = $this->convertAdjacencyListToTree("root",$arrRows,'name','parent','menu');
            // echo '<pre>',print_r($menu),'</pre>';

            // display menu
            return $this->renderMenu($menu,1);
        }
        /*
        * Convert adjacency list to hierarchical tree
        *
        * @param value of root level parent most likely null or 0
        * @param array result
        * @param str name of primary key column
        * @param str name of parent_id column - most likely parent_id
        * @param str name of index that children will reside ie. children, etc
        * @return array tree
        */
        function convertAdjacencyListToTree($intParentId,&$arrRows,$strIdField,$strParentsIdField,$strNameResolution) {

            $arrChildren = array();

            for($i=0;$i<count($arrRows);$i++) {
                if($intParentId === $arrRows[$i][$strParentsIdField]) {
                    $arrChildren = array_merge($arrChildren,array_splice($arrRows,$i--,1));
                }
            }
            $intChildren = count($arrChildren);
            if($intChildren != 0) {
                for($i=0;$i<$intChildren;$i++) {
                    $arrChildren[$i][$strNameResolution] = $this->convertAdjacencyListToTree($arrChildren[$i][$strIdField],$arrRows,$strIdField,$strParentsIdField,$strNameResolution);
                }        
            }
            return $arrChildren;

        }

        /*
        * Theme menu
        *
        * @param array menu
        * @param runner (depth)
        * @return str themed menu
        */
        function renderMenu($menu,$runner) {

            $out = '';

            if(empty($menu)) {
                return $out;
            }
            if($runner>1)
            {
                $out.='<ul id="'.$this->name."-".$runner.'">';
            }
            else
            {
                $out.='<ul id="'.$this->name.'">';
            }
            $menunew=array();
            foreach($menu as $link)
            {
                $menunew[$link["sort"]][]=$link;
            }
            ksort($menunew);
            $menu=array();
            foreach($menunew as $arrLink)
            {
                foreach($arrLink as $link)
                {
                    $menu[]=$link;
                }
            }
            foreach($menu as $link)
            {
                $isJavascript=false;
                ///to hold the parameter in the <a> tag
                $linkParam="";
                if(isset($link["javascript"]) && $link["javascript"]!==false)
                {
                    $isJavascript=true;
                    $arrJavascript=$link["javascript"];
                    $tmp="";
                    foreach($arrJavascript as $event=>$func)
                    {
                        $tmp=" {$event}='{$func}' ";
                    }
                    $urlParamWithQ="javascript:void(0);";
                    $linkParam=$tmp;
                }
                else
                {
                    $arrUrlParam=array();
                    if($link["module"]!==false)
                    {
                        $arrUrlParam[]="module={$link["module"]}";
                    }
                    if($link["action"]!==false)
                    {
                        $arrUrlParam[]="action={$link["action"]}";
                    }
                    if($link["switch"]!==false)
                    {
                        $arrUrlParam[]="switch={$link["switch"]}";
                    } 
                    if($link["url"]!==false)
                    {
                        $arrUrlParam[]=$link["url"];
                    }

                    $urlParamWithQ="index.php";
                    if(!empty($arrUrlParam))
                    {
                        $urlParamWithQ="index.php?".implode("&",$arrUrlParam);
                    }
                }
                $curMod=  ClsNaanalRequest::getInstance()->getModule();
                $curAct= ClsNaanalRequest::getInstance()->getAction();
                if($curMod && $curMod==$link["module"] && ((empty($link["action"]) && $curAct=="create") || $curAct==$link["action"]))
                {
                    $renderMenu=$this->renderMenu($link['menu'],($runner+1));
                    $menuEndClass=""; 
                    if(empty($renderMenu))
                    {
                        $menuEndClass="menutail ";
                    }
                    $out.= sprintf(
                        '<li class="%sdepth-%u menu-active"><span><a %s href="%s">%s</a></span>%s</li>'
                        ,$menuEndClass
                        ,$runner
                        ,$linkParam
                        ,"{$urlParamWithQ}"
                        ,$link['caption'] 
                        ,$renderMenu
                    );
                }
                else
                {
                    $renderMenu=$this->renderMenu($link['menu'],($runner+1));
                    $menuEndClass="";
                    if(empty($renderMenu))
                    {
                        $menuEndClass="menutail ";
                    }
                    $out.= sprintf(
                        '<li class="%sdepth-%u"><span><a %s href="%s">%s</a></span>%s</li>'
                        ,$menuEndClass
                        ,$runner
                        ,$linkParam
                        ,"{$urlParamWithQ}"
                        ,$link['caption'] 
                        ,$renderMenu
                    );
                }
            }

            $out.='</ul>';
            return $out;

        }
	function render($arrMenu=array())
	{
            $arrMenu=empty($arrMenu)?$this->arrMenu:$arrMenu;
		$ccp=getCurrentControlPanel();//trace($ccp);
		$admin=false;
		if(isLogged()) 
		{
			$admin=isAdminUser();//trace($admin);
			$arrPermission=getUserPermission();//trace($arrPermission); 
		}
		$menu='<ul class="'.$this->name.'">';
		foreach($arrMenu as $module=>$arrAction)
		{
			foreach($arrAction as $action=>$arrSwitch)
			{
				foreach($arrSwitch as $arrData) 
				{
					if(isset($arrData["controlpanel"]))
					{
						if(!in_array($ccp, $arrData["controlpanel"])) continue;
					}
					if($admin)
					{
						if($module!="logout")
						if(!isset($arrData["isadmin"]) || empty($arrData["isadmin"])) 
						{
							continue;
						}     
						if(!isset($arrData["url"])) continue;         
						if($action=="default")
							$url="page={$module}";
						else  
							$url="page={$module}&amp;action={$action}";
					}
					else 
					{
						if(getControlPanelConfig("ENABLE_ROLE")=="false")
						{        
						}
						else
						{
							if(!($module=="usedatabase" || $module=="usersettings" || $module=="user") && $action!="default" && !isset($arrPermission[$module][$action])) 
                                                        {
                                                            continue;
                                                        } 
						}
						if($action=="divider") { $menu=$menu.'<li><hr /></li>';continue; }
						if(!isset($arrData["url"])) continue;
						if($action=="default")
							$url="page={$module}";
						else  
							$url="page={$module}&amp;action={$action}";
						//if(isset($arrData["controlpanel"]) && !in_array($loginpanel,$arrData["controlpanel"])) continue;
						if(isset($arrData["isadmin"]) && $arrData["isadmin"]===true) continue;
					}
                                        $basename=URL_BASE_FILE_NAME;
					$alt=isset($arrData["alt"])?" alt=\"".$arrData["alt"]."\"":"";
					$title=isset($arrData["title"])?" title=\"".$arrData["title"]."\"":"";
					if(empty($arrData["url"]))
						$menu=$menu.'<li><a href="'.$basename.'?'.$url.'"'.$alt.''.$title.'>'.$arrData["caption"].'</a></li>';
					else
						$menu=$menu.'<li><a href="'.$basename.'?'.$url."&amp;".$arrData["url"].'"'.$alt.''.$title.'>'.$arrData["caption"].'</a></li>';
				}
			}
		}
		$menu=$menu.'</ul>';
		return $menu;
	}
}
?>